import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'

// 加载数据时打开和关闭动效对象
const loading = {
  loadingInstance: null, // Loading实例
  open: function () { // 打开加载
    //console.log('加载中', this.loadingInstance)
    if (this.loadingInstance === null) { // 创建单例, 防止切换路由重复加载
      //console.log('创建加载实例..')
      this.loadingInstance = Loading.service({
        text: '系统加载中',
        target: '.main', // 效果显示区域
        background: 'rgba(0, 0, 0, 0.5)' // 加载效果
      })
    }
  },
  close: function () { // 关闭加载
    if (this.loadingInstance !== null) {
      this.loadingInstance.close()
      //console.log('结束加载')
    }
    this.loadingInstance = null // 关闭后实例重新赋值null, 下次让它重新创建
  }
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 打开加载窗口
    loading.open()
    const token = store.getters.token;
    if (token) {
      // 设置头文件
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config
  },
  error => {
    // do something with request error
    // 关闭加载窗口
    loading.close()
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 关闭加载窗口
    loading.close()

    const res = response.data
    /**
      * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
      * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
      */
    // // if the custom code is not 20000, it is judged as an error.

    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   // rejection
    //   return Promise.reject(new Error("111"))
    //   // return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    return res
    // }
  },
  error => {
    // 关闭加载窗口
    loading.close()
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
